package com.jiezuo.flowable.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiezuo.common.util.StringUtil;
import com.jiezuo.common.vo.PageVo;
import com.jiezuo.flowable.entity.MessageRouterDetails;
import com.jiezuo.flowable.mapper.MessageRouterDetailsMapper;
import com.jiezuo.flowable.service.MessageRouterDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.ui.modeler.domain.AbstractModel;
import org.flowable.ui.modeler.serviceapi.ModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description 消息路由配置详情表
 * @author 庞留杰
 * @date 2024/08/22 08:59
 * @version V1.0
 **/
@Transactional
@Slf4j
@Service
public class MessageRouterDetailsServiceImpl extends ServiceImpl<MessageRouterDetailsMapper, MessageRouterDetails> implements MessageRouterDetailsService {

    @Autowired
    ModelService modelService;

    @Override
    public IPage<MessageRouterDetails> findPage(PageVo pageVo, MessageRouterDetails messageRouterDetails) {
        /*QueryWrapper<MessageRouterDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete","0");
        return this.page(initMpPage,queryWrapper);*/
        List<MessageRouterDetails> list = getDetails(messageRouterDetails);
        long page_number = pageVo.getPage_number() != 0 ? pageVo.getPage_number() : 1L;
        long page_size = pageVo.getPage_size() != 0 ? pageVo.getPage_size() : 10L;
        int fromIndex = ((int) (page_number - 1) * (int) page_size);
        int toIndex = ((int) page_number) * ((int) page_size);
        if (toIndex > list.size()) {
            toIndex = list.size();
        }
        List<MessageRouterDetails> sub = list.subList(fromIndex, toIndex);
        Page initMpPage = new Page(); // Page page = new Page(current, size, count);
        initMpPage.setSize(page_size);
        initMpPage.setCurrent(page_number);
        initMpPage.setTotal(list.size());
        initMpPage.setRecords(sub);
        return initMpPage;
    }

    @Override
    public List<MessageRouterDetails> findList(MessageRouterDetails messageRouterDetails) {
        /*QueryWrapper<MessageRouterDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete","0");
        List<MessageRouterDetails> list = this.list(queryWrapper);*/
        List<MessageRouterDetails> list = getDetails(messageRouterDetails);
        return list;
    }

    @Override
    public MessageRouterDetails findById(String id) {
        return this.getById(id);
    }

    @Override
    public boolean add(MessageRouterDetails messageRouterDetails) {
        return this.save(messageRouterDetails);
    }

    @Override
    public boolean update(MessageRouterDetails messageRouterDetails) {
        return this.updateById(messageRouterDetails);
    }

    @Override
    public boolean delete(String id) {
        MessageRouterDetails messageRouterDetails = new MessageRouterDetails();
        messageRouterDetails.setId(id);
        messageRouterDetails.setIs_delete("1");
        return this.updateById(messageRouterDetails);
    }

    public List<MessageRouterDetails> getDetails(MessageRouterDetails messageRouterDetails) {
        List<AbstractModel> models = modelService.getModelsByModelType(0);
        String type = messageRouterDetails.getType();
        String flow_name = messageRouterDetails.getFlow_name();
        if (StringUtil.isNotEmpty(type)) {
            models = models.stream().filter(it -> it.getKey().contains(type.trim())).collect(Collectors.toList());
        }
        if (StringUtil.isNotEmpty(flow_name)) {
            models = models.stream().filter(it -> it.getName().contains(flow_name.trim())).collect(Collectors.toList());
        }
        log.info("查询到的流程数量共计：{}", models.size());
        List<MessageRouterDetails> list = new ArrayList<>();
        for (AbstractModel model : models) {
            String json = model.getModelEditorJson();
            JSONObject parse = (JSONObject) JSON.parse(json);
            JSONObject properties = (JSONObject) parse.get("properties");
            String module = (String) properties.get("name");
            String process_id = (String) properties.get("process_id");
            JSONArray arr = (JSONArray) parse.get("childShapes");
            for (Object obj : arr) {
                JSONObject childShapes = (JSONObject) obj;
                sub(childShapes, module, process_id, "", list);
            }
        }
        return list;
    }

    void sub(JSONObject childShapes, String module, String process_id, String subprocess, List<MessageRouterDetails> list) {
        JSONObject csProperties = (JSONObject) childShapes.get("properties");
        JSONObject stencil = (JSONObject) childShapes.get("stencil");
        String id = (String) stencil.get("id");
        if (!"SequenceFlow".equals(id)
                && !"ServiceTask".equals(id)
                && !"InclusiveGateway".equals(id) && !"ExclusiveGateway".equals(id)
                && !"StartNoneEvent".equals(id) && !"EndNoneEvent".equals(id)) {
            String activity_id = String.valueOf(csProperties.get("overrideid"));
            String name = String.valueOf(csProperties.get("name"));
            if ("SubProcess".equals(id)) {
                subprocess = "[子流程：" + name + "]";
            } else {
                /*String sql = "INSERT INTO sys_message_router(`is_delete`, `created_by`, `created_time`, `updated_by`, `updated_time`, `note`, `name`, `type`, `activity_id`, `router`, `state`, `module`,`flow_name`,`task_name`)" +
                        " VALUES (0, 1, '2024-08-21 10:51:41', 1, '2024-08-21 10:51:41', NULL, '%s', '%s', '%s', null, 1, '%s', '%s', '%s');";
                String format = String.format(sql, name + subprocess, process_id, activity_id, module, module, name + subprocess);
                System.out.println(format);*/
                MessageRouterDetails detail = new MessageRouterDetails();
                detail.setFlow_name(module);
                detail.setTask_name(name + subprocess);
                detail.setType(process_id);
                detail.setActivity_id(activity_id);
                list.add(detail);
            }
            JSONArray arr = (JSONArray) childShapes.get("childShapes");
            if (arr != null) {
                for (Object obj : arr) {
                    JSONObject childShapes1 = (JSONObject) obj;
                    sub(childShapes1, module, process_id, subprocess, list);
                }
            }
        }
    }


}
